package com.nowcoder.community.d_controller;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.a_entity.Message;
import com.nowcoder.community.a_entity.Page;
import com.nowcoder.community.a_entity.User;
import com.nowcoder.community.c_service.MessageService;
import com.nowcoder.community.c_service.UserService;
import com.nowcoder.community.z_util.CommunityUtil;
import com.nowcoder.community.z_util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import com.nowcoder.community.z_util.CommunityConstant;

import java.util.*;

/**
 * <p>——————————————————————————————————————————————-————
 * <p>   【名字】cookie工具类 【所属包】com.nowcoder.community.d_controller
 * <p>
 * <p>   【谁调用我】首页点击消息按钮
 * <p>
 * <p>   【调用我干什么】查询所有1级私信并回显
 * <p>——————————————————————————————————————————————-————
 */

@Controller
@RequestMapping//"/letter" 不能写controller里！！1
public class MessageController implements CommunityConstant {
    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    /**
     * <p>——————————————————————————————————————————————-————
     * <p>   按私信用户不同，显示所有用户的最末私信
     * <p>——————————————————————————————————————————————-————
     */
    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public String showAllLastMessage(Model model, Page page){
        User user = hostHolder.getUser();

        //分页按钮的其他设置
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));//总数-为了最后一页的offset


        //分页显示{这个userid的所有其他用户私信的首条}（其中首页选择默认值offset=1，后面按分页按钮在html前台计算出的offset）
        List<Message> msgList = messageService.findConversations(user.getId(),page.getOffset(),page.getLimit());
        //拆开，每个msg里面还涉及补充信息
        List<Map<String, Object>> conversations = new ArrayList<>();
        for(Message msg:msgList){
            Map<String, Object> map = new HashMap<>();
            map.put("conversation",msg);
            map.put("letterCount",messageService.findLetterCount(msg.getConversationId()));
            //因为无论1->2 2->1 conid都是1_2 好用！！！！！！！！！！！！！！
            map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(),msg.getConversationId()));

            //头像取不是host-userid的另一个人USer pojo ，th智能拿get
            int tarUserId = user.getId()==msg.getFromId() ? msg.getToId(): msg.getFromId();
            map.put("targetUserPojo", userService.findUserByid(tarUserId));

            conversations.add(map);
        }
        model.addAttribute("conversations",conversations);


        //这个hostuser的总未读消息
        model.addAttribute("letterUnreadCount",
                messageService.findLetterUnreadCount(user.getId(),null));//这里动态null的sql拼接，就是查所有

        return "moban/site/letter";
    }

//    @RequestMapping(path = "/detail/${rowId}" ,method = RequestMethod.GET)
//    public String gotoDetailLetter(Model model,
//                                   @PathVariable("rowId")int rowId){
//
//        return "moban/site/letter-detail";
//
//    }
    @RequestMapping(path = "/letter/detail/{rowId}",method = RequestMethod.GET)
    public String gotoDetailLetter(Model model,
                                   Page page,
                                   @PathVariable("rowId")String rowId){
        User user = hostHolder.getUser();


        //分页按钮的其他设置
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));//总数-为了最后一页的offset

        //私信分页显示
        List<Message> detailLetterList = messageService.findLetters(rowId, page.getOffset(),page.getLimit());//从显示path中拿的rowid

        List<Map<String, Object>> letters = new ArrayList<>();
        for(Message msg: detailLetterList){
            Map<String, Object> map = new HashMap<>();
            //这才是每条聊天记录的各种核心
            map.put("letter",msg);

            //拿的pojo-user的详细信息在user表
            map.put("fromUser",userService.findUserByid(msg.getFromId()));

            letters.add(map);
        }

        model.addAttribute("letters",letters);


        //最上方显示谁发来的
        //拆解rowid111_112[java不知道哪个另一个，要通过host-userid判断排除]
        String[] ids = rowId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);
        int res= 0;
        if (hostHolder.getUser().getId() == id0) {
            model.addAttribute("target",userService.findUserByid(id1));
        } else {
            model.addAttribute("target",userService.findUserByid(id0));
        }


        //已读更新
        //先获取List<id>
        List<Integer> idList = new ArrayList<>();
        //加if防止sql里null-List参数报错

        for(Message let:detailLetterList){
            //把对方发给自己的才用改已读（自己发的需要对方改已读）
            if(hostHolder.getUser().getId()==let.getToId() && let.getStatus()==0)
                idList.add(let.getId());//极少见的，用了letter的id
        }
        if( idList.size()>0){
            //批量更新，点击回显的分页内容改已读
            messageService.readedMessgae(idList);
        }




        return "moban/site/letter-detail";

    }



    /**
     * <p>——————————————————————————————————————————————-————
     * <p>   ajax直接拿2String，不用model
     * <p>——————————————————————————————————————————————-————
     */
    @ResponseBody
    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    public String addMessageButton(String toName,String content){//这里笨想就知道应该同名
        User tarUser = userService.findUserByName(toName);

        //插入insert肯定新new
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());//把所有的（sql最开始无默认值的都填进去即可，所有都填就不怕少了！）
        message.setToId(tarUser.getId());
        message.setCreateTime(new Date());

        //合成：小永前111_112
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        //content先set，再给seviceget出来从而敏感词处理，
        message.setContent(content);
        messageService.addMessage(message);

        return CommunityUtil.javaToJsonString(0,"发送私信成功啦！！！！");//只返回个状态码？
    }




    /**
     * <p>——————————————————————————————————————————————-————
     * <p> 开始系统通知核心页面交互Con
     * <p>——————————————————————————————————————————————-————
     */
    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticeList(Model model) {
        User user = hostHolder.getUser();

        // 查询评论类通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        Map<String, Object> messageVO = new HashMap<>();
        if (message != null) {
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserByid((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unread", unread);
        }
        //bug(上来没有通知 ，老师没写)
        if(message==null) messageVO=null;
        model.addAttribute("commentNotice", messageVO);

        // 查询点赞类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        messageVO = new HashMap<>();
        if (message != null) {
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserByid((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", unread);
        }
        //bug(上来没有通知 ，老师没写)
        if(message==null) messageVO=null;
        model.addAttribute("likeNotice", messageVO);

        // 查询关注类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        messageVO = new HashMap<>();
        if (message != null) {
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserByid((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", unread);
        }
        //bug(上来没有通知 ，老师没写)
        if(message==null) messageVO=null;
        model.addAttribute("followNotice", messageVO);

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "moban/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {
        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.findUserByid((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知作者
                map.put("fromUser", userService.findUserByid(notice.getFromId()));

                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices", noticeVoList);


        /**
         * <p>——————————————————————————————————————————————-————
         * <p> 先显示出来，之后在处理未读
         * <p>——————————————————————————————————————————————-————
         */
        // 设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readedMessgae(ids);
        }

        return "moban/site/notice-detail";
    }
    //工具方法——只用一次
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }
}
